<?php
class RakutenWidget extends WP_Widget {
	public $name = "Rakuten";
	public $description = "楽天の商品検索用のWidget";
	public $control_options = array(
		'title' => 'Rakuten live search',
	);

	function __construct ()
	{
		$widget_options = array(
			'classname' => __CLASS__,
			'description' => $this->description
		);
		parent::__construct(__CLASS__, $this->name, $widget_options,$this->control_options);
	}

	static function register_this_widget ()
	{
		register_widget(__CLASS__);
	}

	static function head ()
	{
//		wp_enqueue_script('jquery');
	}

	static function parse ($tpl, $hash) {
		foreach ($hash as $key => $value) {
			$tpl = str_replace('[+'.$key.'+]', $value, $tpl);
		}
		return $tpl;
	}

	static function get_content () {
		return "<div id='RakutenSearchWidget'></div>";
	}

	//display in template
	function widget ($args, $instance) {
		$src = plugins_url('js/RakutenWidgetSearch.js.php',__DIR__);
		wp_register_script(__CLASS__, $src);
		wp_enqueue_script('jquery');
		wp_enqueue_script(__CLASS__);
		$placeholder = array_merge($args,$instance);
		$placeholder['content'] = RakutenWidget::get_content();
		$tpl = file_get_contents(dirname(dirname(__FILE__)) . '/tpls/widget.tpl');
		echo RakutenWidget::parse($tpl, $placeholder);
	}

	//Widget options
	function form ($instance) {
		$placeholders = array();
		foreach ($this->control_options as $key => $val)
		{
			$placeholders[$key . '.id'] = $this->get_field_id($key);
			$placeholders[$key . '.name'] = $this->get_field_name($key);

			if (isset($instance[$key])) {
				$placeholders[$key . '.value'] = esc_attr($instance[$key]);
			} else {
				$placeholders[$key . '.value'] = $this->control_options[$key];
			}
		}


		$tpl = file_get_contents(dirname(dirname(__FILE__)) . '/tpls/widget_controls.tpl');
		echo RakutenWidget::parse($tpl, $placeholders);

	}


}
?>